// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// j [author] rhyme_lph
// F [email]  rhymelph@gmail.com
// J [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_contacts_provider.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_view_provider.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/dash_board/contacts_item.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:pull_to_refresh/pull_to_refresh.dart';

class DashboardContactsView extends StatefulWidget {
  @override
  _DashboardContactsViewState createState() => _DashboardContactsViewState();
}

class _DashboardContactsViewState extends State<DashboardContactsView>
    with
        StatefulPresenter<DashboardContactsView, DashboardViewProvider,
            DashboardContactsProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) =>
      !Config.hasPermission(PermissionUtils.businessContact)
          ? buildNoPermissionWidget(context)
          : SmartRefresher(
              controller: provider.refreshController,
              onRefresh: provider.onRefresh,
              enablePullUp: false,
              child: ListView(
                physics: const ClampingScrollPhysics(),
                key: PageStorageKey("Tab2"),
                children: [
                  _buildFilterWidget(),
                  listBuilder<int>(
                    selector: (_, __) => __.dataList?.length,
                    builder: (BuildContext context, int value, Widget child) =>
                        value == null
                            ? super.buildLoadingWidget(context)
                            : value == 0
                                ? super.buildEmptyWidget(provider, context)
                                : listBuilder<Map>(
                                    selector: (_, __) => Map.from(__.groupMap),
                                    builder: (BuildContext context, Map value,
                                            Widget child) =>
                                        Column(
                                      children: _buildContactList(),
                                    ),
                                  ),
                  ),
                ],
              ),
            );

  Widget _buildFilterWidget() => Container(
        padding: EdgeInsets.only(top: getDp(20), bottom: getDp(25)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buildSortContactSelect(),
            PressedOpacityButton(
              onPressed: provider.onNavViewAll,
              padding: EdgeInsets.symmetric(horizontal: getDp(20)),
              child: Text(
                S.current.view_all,
                style: TextStyle(
                  color: aceBlueColor,
                  fontSize: getSp(16),
                  fontWeight: FontWeight.w700,
                  height: 14 / 16,
                ),
              ),
            )
          ],
        ),
      );

  Widget buildSortContactSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectSortContact,
            ),
        selector: (_, __) => __.currentSelectSortContact);
  }

  List<Widget> _buildContactList() {
    List<Widget> child = [];
    for (final item in provider.groupMap.entries) {
      if (item.key.isNotEmpty) {
        child.add(ListHeaderItem(
          title: item.key,
        ));
      }
      child.addAll(item.value.map((e) => ContactsItem(
            onClickStar: () => provider.onClickStar(e),
            onTap: () => provider.onNavContactDetail(e),
            amount: CashUtils.formatCashAmount(
              ((e.receivingAmount ?? 0.0) - (e.payingAmount ?? 0.0)).abs(),
            ),
            isGet: (e.receivingAmount ?? 0.0) - (e.payingAmount ?? 0.0) > 0,
            title: e.name,
            isSelect: e.isFavorite == 1,
            isOverdue: e.isOverdue == 1,
            hasCreditBalance: (e.totalUnpaidCredit + e.totalUnpaidDebit) > 0,
            isLastItem: item.value.last == e,
          )));
    }
    return child;
  }
}
